package game

import (
	"log"

	"gitee.com/yysama/Kindling_civilization/core/config"
	"github.com/hajimehoshi/ebiten/v2"
)

type game struct {
	window_width  int // 屏幕宽
	window_height int // 屏幕高

	last_scence  *ebiten.Game   // 当前场景
	scence_statk []*ebiten.Game // 场景栈
	is_run       bool           // 运行中
}

var (
	this *game
)

func Instance(cfg *config.Config) *game {
	if this != nil {

	} else {
		this = &game{
			window_width:  cfg.WindowWidth,
			window_height: cfg.WindowHeight,
			last_scence:   nil,
			scence_statk:  make([]*ebiten.Game, 0),
			is_run:        false,
		}
		ebiten.SetWindowSize(cfg.WindowWidth, cfg.WindowHeight)
	}

	return this
}

func (this *game) Run() {
	if !this.is_run {
		this.is_run = true
		if e := ebiten.RunGame(this); e != nil {
			log.Fatal(e)
		}
	}
}

func (this *game) Update() error {
	if this.last_scence != nil {
		return (*this.last_scence).Update()
	}

	return nil
}

func (this *game) Draw(screen *ebiten.Image) {
	(*this.last_scence).Draw(screen)
}

func (this *game) Layout(outsideWidth, outsideHeight int) (int, int) {
	return this.window_width, this.window_height
}

func (this *game) Size() (width, height int) {
	return this.window_width, this.window_height
}

// 切换场景
func (this *game) SetScence(scence ebiten.Game) *game {
	this.last_scence = &scence

	return this
}

// 暂停场景
func (this *game) PauseScence() *game {
	this.PushScence(*this.last_scence)
	this.last_scence = nil

	return this
}

// push 场景
func (this *game) PushScence(scence ebiten.Game) *game {
	this.scence_statk = append(this.scence_statk, this.last_scence)

	return this
}

// pop 场景
func (this *game) PopScence(scence ebiten.Game) *game {
	this.scence_statk = append(this.scence_statk, this.last_scence)
	if len(this.scence_statk) > 0 {
		count := len(this.scence_statk)
		this.last_scence = this.scence_statk[count-1]
		this.scence_statk = this.scence_statk[0 : count-1]
	}
	return this
}
